﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class UserController : BaseController
    {
        Maticsoft.Model.T_User M_user = new Maticsoft.Model.T_User();
        Maticsoft.Model.T_Equipment M_equipment = new Maticsoft.Model.T_Equipment();
        #region 初始化
        public void setViewData()
        {
            Maticsoft.BLL.T_User bll = new Maticsoft.BLL.T_User();
            string id = Session["UserInfo"].ToString();
            M_user = bll.GetModel(id);
            ViewData["UserName"] = M_user.Name;
        }

        public void GetUser()
        {
            try
            {
                Maticsoft.BLL.T_User bll = new Maticsoft.BLL.T_User();
                string id = Session["UserInfo"].ToString();
                M_user = bll.GetModel(id);
            }
            catch
            {
                Session["UserInfo"] = null;
            }
        }

        public void setViewData(bool set)
        {
            if (set)
            {
                string[] offices = new string[4]{
                    "内科","外科","妇产科","儿科"
                };
                Maticsoft.BLL.T_User bll = new Maticsoft.BLL.T_User();
                string id = Session["UserInfo"].ToString();
                M_user = bll.GetModel(id);
                ViewData["UserName"] = M_user.Name;
                ViewData["UserPassword"] = M_user.Password;
                ViewData["UserOffice"] = offices[M_user.Offices - 3];
                ViewData["UserId"] = M_user.Id;
                ViewData["UserIllness"] = M_user.Illness;
                ViewData["UserBed"] = M_user.Bed;
                ViewData["UserSex"] = M_user.Sex.Trim();
                ViewData["UserOld"] = M_user.Old;
                ViewData["UserEmail"] = M_user.Email;
                ViewData["UserTel"] = M_user.Tel;
                ViewData["UserPhoto"] = M_user.Photo;
                ViewData["UserHeight"] = M_user.Height;
                ViewData["UserWeight"] = M_user.Weight;
                ViewData["UserTime"] = M_user.BeHosptial;
                ViewData["UserDoctor"] = M_user.DoctorName;
                ViewData["DateTime"] = DateTime.Now.ToString("yyyy-MM-dd");
                Maticsoft.BLL.T_Doctor bll_doctor = new Maticsoft.BLL.T_Doctor();

                List<Maticsoft.Model.T_Doctor> doctor = (bll_doctor.GetModelList("Name='" + M_user.DoctorName.Trim() + "'"));
                if (doctor.Count > 0)
                {
                    ViewData["UserDoctorTel"] = doctor[0].Tel;
                    ViewData["UserDoctorEmail"] = doctor[0].Email;
                }

            }
            else
            {
                Maticsoft.BLL.T_User bll = new Maticsoft.BLL.T_User();
                string id = Session["UserInfo"].ToString();
                M_user = bll.GetModel(id);
                ViewData["UserName"] = M_user.Name;
                ViewData["UserNum"] = M_user.Name;
                ViewData["TalkNum"] = M_user.Name;
                ViewData["DoctorNum"] = M_user.Name;
                ViewData["UserNum"] = M_user.Name;
            }
        }

        public bool InitData()
        {
            GetUser();
            Maticsoft.BLL.T_Equipment bll = new Maticsoft.BLL.T_Equipment();
            List<Maticsoft.Model.T_Equipment> equipments = bll.GetModelList("UserId='" + M_user.Id + "'");
            if (equipments.Count > 0)
            {
                M_equipment = equipments[0];
                return true;
            }
            return false;
        }
        #endregion

        #region 首页
        public ActionResult Index()
        {
            setViewData();
            return View();
        }
        #endregion

        #region  医生
        public ActionResult Widgets()
        {
            setViewData();
            return View();
        }
        #endregion

        #region 实时数据
        public ActionResult Charts()
        {
            setViewData();
            return View();
        }
        #endregion

        #region 历史数据
        public ActionResult Tables()
        {
            setViewData();
            return View();
        }
        #endregion

        #region 病历
        public ActionResult Forms()
        {
            setViewData(true);
            return View();
        }
        #endregion

        #region 个人设置
        public ActionResult Person()
        {
            setViewData(true);
            return View();
        }
        #endregion

        #region 获得数据
        public JsonResult Json()
        {
            var res = new JsonResult();
            setViewData();
            if (InitData() == true)
            {
                Maticsoft.BLL.T_Monitor bll = new Maticsoft.BLL.T_Monitor();
                List<Maticsoft.Model.T_Monitor> monitors = bll.GetModelList("((Equipment='" + M_equipment.Id + "')AND(NowTime='*'))");
                res.Data = monitors;
            }
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return res;
        }
        #endregion

        #region 获得病历
        public ActionResult GetHistory()
        {
            GetUser();
            string history_str = "";
            Maticsoft.BLL.T_History bll = new Maticsoft.BLL.T_History();
            string datetime = Request["time"];
            List<Maticsoft.Model.T_History> historys = bll.GetModelList("(UserName='" + M_user.Name + "')AND((Time>='" + Request["time"] + " 00:00:00')AND(Time<='" + Request["time"] + " 23:59:59'))");
            if (historys.Count > 0)
            {
                foreach (Maticsoft.Model.T_History history in historys)
                {
                    history_str = history.Time.ToString("HH:mm") + "\r" + history.Chars + "\r";
                }
            }
            return Content(history_str);
        }
        #endregion

        #region 发送邮件
        public ActionResult SendEmail()
        {
            string chars = Request["Chars"];
            string name = Request["Name"];
            string email = Request["Email"];
            if ((String.IsNullOrEmpty(chars)) || (String.IsNullOrEmpty(name)) || (String.IsNullOrEmpty(email)))
            {
                return Content("Wait");
            }
            else
            {
                GetUser();
                Maticsoft.BLL.T_Doctor bll_doctor = new Maticsoft.BLL.T_Doctor();
                List<Maticsoft.Model.T_Doctor> doctor = (bll_doctor.GetModelList("Name='" + M_user.DoctorName.Trim() + "'"));
                return Content(SendMailLocalhost(email, doctor[0].Email, chars, name));
            }
        }

        public string SendMailLocalhost(string from, string to, string chars, string Name)
        {
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add(to);
            msg.From = new MailAddress(from, Name, System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
            msg.Subject = "来自您的客户" + Name + "的邮件";//邮件标题 
            msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码 
            msg.Body = chars;//邮件内容 
            msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码 
            msg.IsBodyHtml = false;//是否是HTML邮件 
            msg.Priority = MailPriority.High;//邮件优先级 

            SmtpClient client = new SmtpClient();
            client.Host = "localhost";
            object userState = msg;
            try
            {
                client.SendAsync(msg, userState);
                //简单一点儿可以client.Send(msg); 
                return "OK";
            }
            catch (System.Net.Mail.SmtpException ex)
            {

            }
            return "No";
        }
        #endregion

        #region 获得聊天
        public JsonResult GetTalk()
        {
            GetUser();
            var res = new JsonResult();
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            Maticsoft.BLL.T_Talk bll = new Maticsoft.BLL.T_Talk();
            List<Maticsoft.Model.T_Talk> talks = bll.GetModelList("UserName='" + M_user.Name + "'");
            if (talks.Count > 0)
            {
                List<Maticsoft.Model.T_Talk> talk_list = new List<Maticsoft.Model.T_Talk>();
                if (talks.Count > 10)
                {
                    for (int i = 0; i < 10; i++)
                    {
                        talk_list.Add(talks[talks.Count - i - 1]);
                    }
                }
                else
                {
                    for (int i = 0; i < talks.Count; i++)
                    {
                        talk_list.Add(talks[talks.Count - i - 1]);
                    }
                }
                res.Data = talk_list;
                return res;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 添加聊天
        public ActionResult AddTalk()
        {
            string mess = Request["mess"];
            GetUser();
            Maticsoft.Model.T_Talk talk = new Maticsoft.Model.T_Talk();
            Maticsoft.BLL.T_Talk bll = new Maticsoft.BLL.T_Talk();
            talk.UserName = M_user.Name;
            talk.DoctorName = M_user.DoctorName;
            talk.Time = DateTime.Now;
            talk.Talker = M_user.Name;
            talk.Talk = mess;
            if (bll.Add(talk))
            {
                return Content("OK");
            }
            return Content("No");
        }
        #endregion

        #region 添加计划
        public ActionResult AddPlan()
        {
            string mess = Request["mess"];
            GetUser();
            Maticsoft.Model.T_Plan plan = new Maticsoft.Model.T_Plan();
            Maticsoft.BLL.T_Plan bll = new Maticsoft.BLL.T_Plan();
            plan.Name = M_user.Name;
            plan.PlanDate = DateTime.Now;
            plan.Plan = mess;
            plan.Del = false;
            if (bll.Add(plan))
            {
                return Content("OK");
            }
            return Content("No");
        }
        #endregion

        #region 获得计划
        public ActionResult GetPlan()
        {
            GetUser();
            var res = new JsonResult();
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            Maticsoft.BLL.T_Plan bll = new Maticsoft.BLL.T_Plan();
            List<Maticsoft.Model.T_Plan> talks = bll.GetModelList("DoctorName='" + M_user.Name + "'");
            if (talks.Count > 0)
            {
                List<Maticsoft.Model.T_Plan> talk_list = new List<Maticsoft.Model.T_Plan>();
                if (talks.Count > 10)
                {
                    for (int i = 0; i < 10; i++)
                    {
                        talk_list.Add(talks[talks.Count - i]);
                    }
                }
                else
                {
                    for (int i = 0; i < talks.Count; i++)
                    {
                        talk_list.Add(talks[talks.Count - i - 1]);
                    }
                }
                res.Data = talk_list;
                return res;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 个人设置
        public ActionResult SetUser()
        {

            Maticsoft.BLL.T_User bll = new Maticsoft.BLL.T_User();
            string name = Request["name"];
            string sex = Request["sex"];
            int old = int.Parse(Request["old"]);
            string tel = Request["tel"];
            string email = Request["email"];
            long offices = 6;
            string office = Request["offices"];
            string weigh = Request["weigh"];
            int height = int.Parse(Request["height"]);
            string time = Request["time"];
            switch (office)
            {
                case "内科": offices = 3; break;
                case "外科": offices = 4; break;
                case "妇产科": offices = 5; break;
                default
                : break;
            }
            GetUser();
            Maticsoft.Model.T_User user = M_user;
            user.Time_Str = time;
            user.Name = name;
            user.Email = email;
            user.Old = old;
            user.Sex = sex;
            user.Tel = tel;
            user.Offices = offices;
            user.Height = height;
            user.Weight = weigh;
            if (bll.Update(user))
            {
                return Content("OK");
            }
            else
            {
                return Content("NO");
            }

        }
        #endregion

        #region 提交图片
        public ActionResult FileUpload()
        {
            HttpPostedFileBase file = Request.Files["fileUp"];
            if (file != null)
            {
                string fileName = Path.GetFileName(file.FileName);
                string fileExt = Path.GetExtension(file.FileName);
                if (fileExt == "jpg")
                {
                    string dir = "/ImagesPath" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/";
                    Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(dir)));
                    string newFileName = Guid.NewGuid().ToString();

                    string fullDir = dir + newFileName + fileExt;
                    file.SaveAs(Request.MapPath(fullDir));
                    return Content("OK");
                }
            }
            return Content("NO");
        }
        #endregion

        #region 实时数据
        public JsonResult RealTime()
        {
            var res = new JsonResult();
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            string Id = Request["Id"];
           if( InitData())
           {
                Maticsoft.BLL.T_Monitor bll = new Maticsoft.BLL.T_Monitor();
                List<Maticsoft.Model.T_Monitor> monitors = bll.GetModelList("Equipment='" + M_equipment.Id + "'");
                if (monitors.Count > 0) {
                    if (Id == monitors[monitors.Count - 1].Id)
                    {
                        return null;
                    }
                    res.Data = monitors[monitors.Count-1];
                }
                else
                {
                    return null;
                }
           }
           else
           {
               return null;
           }
            return res;
        }
        #endregion
    }
}
